import React from 'react';
import {
  Card,
  Breadcrumb,
  Form,
  Select,
  Button,
  Input,
  Space,
  Radio,
  Upload,
} from 'antd';
import { getChannels } from '@/store/actions/article';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import styles from './index.module.scss';
import { useEffect, useState } from 'react';

import Channel from '@/components/Channel';

import { PlusOutlined } from '@ant-design/icons';

import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import 'react-quill/dist/quill.bubble.css';

import { message } from 'antd';

import { addArticle } from '@/store/actions/article';

// import  {useHistory} from 'react-router-dom'

import { useHistory, useParams } from 'react-router-dom';
import { getArticle, editArticle } from '@/store/actions/article';

export default function Publish() {
  // 获取频道数据
  const channels = useSelector((state) => state.article.channels);
  const dispatch = useDispatch();
  const history = useHistory();

  useEffect(() => {
    dispatch(getChannels());
  }, [dispatch]);

  // 1完成封面类型渲染和切换
  const [type, setType] = useState(1);

  const onTypeChange = (e) => {
    setType(e.target.value);
    setFileList([]);
  };

  // 2 完成封图上传，根据封面类型限制上传的图片张数

  const [fileList, setFileList] = useState([]);

  const onUploadChange = ({ fileList }) => {
    setFileList(fileList);
  };

  const onPreview = (file) => {
    console.log(file);
  };

  const isImageUrl = (file) => {
    console.log('isImageUrl', file);
    return true;
  };

//  存入草稿箱  draft = false   表示不存储草稿箱   draft  为true  则表示存储草稿箱 




  const onFinish = async (values,draft = false) => {
    console.log(values);
    if (type !== fileList.length) {
      return message.warning('请按照选择的封面类型上传图片');
    }
    // 组织提交数据
    const data = {
      ...values,
      cover: {
        type,
        // 后台需要[string]类型
        // 兼容两种数据格式：[{response:{data:{url:'图片地址'}}}]  [{url:'图片地址'}]
        images: fileList.map((item) => item?.response?.data?.url || item.url),
      },

    };

     // 如果有 id  那么就是编辑  
   if(params.id)  {
      data.id= params.id  
      await  dispatch(editArticle(data,draft))
   }else  {
      // 如果没有 id  那么就是添加逻辑  
        await  dispatch(addArticle(data,draft)) 
   }
    message.success('ok');
    history.push('/home/article');
  };

  // 编辑自动填充
  const params = useParams();
  const [myForm] = Form.useForm();
  console.log('forms',myForm)

  useEffect(() => {
    const setFormData = async () => {
      if (params.id) {
        const { title, cover, content, channel_id } = await dispatch(
          getArticle(params.id)
        );
        myForm.setFieldsValue({ title, content, channel_id });
        setType(cover.type);
        setFileList(cover.images.map((item) => ({ url: item })));
      }else  {

        // 点击发布文章，需要重置数据 
          setType(1)
          setFileList([])
          myForm.resetFields()
      }
    };
    setFormData();
  }, [dispatch, myForm]);


//  存储草稿逻辑 
const  saveDraft=async ()=>{
    try {
       const values= await  myForm.validateFields()
        onFinish(values,true)
      
    } catch (error) {
      
    }
}

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <Link to="/article">内容管理</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {params.id ? '修改文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form labelCol={{ span: 4 }} onFinish={onFinish}
        form={myForm}
        >
          <Form.Item
            label="文章标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>

          <Form.Item
            label="所属频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择所属频道' }]}
          >
            {/* 
          <Select  style={{width:400}}>
      {
      channels.map((item)=>(  <Select.Option key={item.id} value={item.id}> {item.name}  </Select.Option>))

      }

          </Select> */}

            <Channel width={400} />
          </Form.Item>

          <Form.Item label="文章封面：">
            {/* 一个FormItem只能有一个元素 */}
            <Form.Item style={{ marginBottom: 0 }}>
              <Radio.Group value={type} onChange={onTypeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {/* 这个位置放Upload组件 */}
            {type > 0 ? (
              <div style={{ marginTop: 16 }}>
                <Upload
                  multiple
                  name="image"
                  listType="picture-card"
                  action="http://geek.itheima.net/v1_0/upload"
                  thumbUrl="http://geek.itheima.net/v1_0/upload"
                  fileList={fileList}
                  onPreview={onPreview}
                  onChange={onUploadChange}
                  defaultFileList={fileList}
                  isImageUrl={isImageUrl}
                >
                  {fileList.length < type ? (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>Upload</div>
                    </div>
                  ) : null}
                </Upload>
              </div>
            ) : null}
          </Form.Item>

          <Form.Item
            label="文章内容："
            name="content"
            wrapperCol={{ span: 16 }}
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill placeholder="请输入文章内容" theme="snow" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {params.id ? '修改文章' : '发布文章'}
              </Button>
              <Button type="primary"  onClick={saveDraft}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
